package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.heima.apis.schedule.IscheduleClient;
import com.heima.model.common.constants.TaskTypeEnum;
import com.heima.model.common.dtos.common.ResponseResult;
import com.heima.model.common.dtos.common.TaskDto;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class WmNewsTaskServiceImpl implements WmNewsTaskService {
    @Autowired
    private IscheduleClient ischeduleClient;
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;
    /**
     * 添加任务到延迟队列中
     * @param newId      文章id
     * @param pulishTime 文章发布时间/任务的执行时间
     */
    @Async
    @Override
    public void addNewsTask(Integer newId, Date pulishTime) {
        //添加任务到延迟服务中
        //封装任务对象用于延迟服务使用
        TaskDto taskDto = new TaskDto();
        //文章发布时间即为任务执行时间
        taskDto.setExecuteTime(pulishTime.getTime());
        taskDto.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        taskDto.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        WmNews wmNews = new WmNews();
        wmNews.setId(newId);
        //将参数放入对象中进行序列化
        taskDto.setParameters(ProtostuffUtil.serialize(wmNews));
        ischeduleClient.addTask(taskDto);
    }

    /**
     * 消费任务，审核文章
     * 每秒拉取一次延迟任务进行审核
     */
    @Override
    @Scheduled(fixedRate = 5000)
    public void scanNewsByTask() {
        ResponseResult response = ischeduleClient.pull(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if (response.getCode().equals(200)&&response.getData()!=null) {
            String jsonString = JSONObject.toJSONString(response.getData());
            TaskDto taskDto = JSONObject.parseObject(jsonString, TaskDto.class);
            WmNews wmNews = ProtostuffUtil.deserialize(taskDto.getParameters(), WmNews.class);
            Integer newsId = wmNews.getId();
            wmNewsAutoScanService.autoScanWmNews(newsId);
        }
    }
}
